package com.itmuch.cloud.study.user.controller;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;

import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import com.itmuch.cloud.study.user.entity.User;
import com.itmuch.cloud.study.user.feign.UserFeignClient;
import com.itmuch.cloud.study.user.service.SSEServer;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Api(tags = "movie模块")
@RestController
public class MovieController
{
    long i = 0L;
    
    @Autowired
    private UserFeignClient userFeignClient;
    
    @PostConstruct
    private void init()
    {
        log.info("Server-Sent Events start");
        new ScheduledThreadPoolExecutor(2).scheduleAtFixedRate(() -> {
            i = (i + 1 + RandomUtils.nextInt(10)) % 101;
            SSEServer.batchSendMessage(String.valueOf(i));
        }, 2000, 500, TimeUnit.MILLISECONDS);
    }
    
    @GetMapping("/sse/connect/{userId}")
    public SseEmitter connect(@PathVariable String userId)
    {
        return SSEServer.connect();
    }
    
    @ApiOperation("查询用户")
    @GetMapping("/user/{id}")
    public User findById(@PathVariable Long id)
    {
        return this.userFeignClient.findById(id);
    }
}
